<template>
	<view class="product-detail">
		<image :src="'/static/product/' + product.imgSrc" mode="aspectFit"></image>
		<view class="product-info">
			<text class="product-name">{{ product.name }}</text>
			<text class="product-price">￥{{ product.price }}</text>
			<view class="quantity-selector">
				<button @click="decreaseQuantity">-</button>
				<input type="number" v-model="quantity" />
				<button @click="increaseQuantity">+</button>
			</view>
			<button @click="addToCart">加入购物车</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				product: {},
				quantity: 1
			}
		},
		onLoad(options) {
			const productId = options.productId;
			this.fetchProductDetail(productId);
		},
		methods: {
			fetchProductDetail(productId) {
				// 调用商品详情接口
				uni.request({
					url: `http://localhost:8080/api/products/${productId}`,
					method: 'GET',
					success: (res) => {
						if (res.data.code === 200) {
							this.product = res.data.data;
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '获取商品详情失败',
							icon: 'none'
						});
					}
				});
			},
			decreaseQuantity() {
				if (this.quantity > 1) {
					this.quantity--;
				}
			},
			increaseQuantity() {
				this.quantity++;
			},
			addToCart() {
				const userInfo = uni.getStorageSync('userInfo');
				if (!userInfo) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}
				// 调用添加购物车接口
				uni.request({
					url: 'http://localhost:8080/api/carts',
					method: 'POST',
					data: {
						userId: userInfo.customerId,
						productId: this.product.productId,
						buyNum: this.quantity,
						name: this.product.name // 添加商品名称
					},
					success: (res) => {
						if (res.data.code === 200) {
							uni.showToast({
								title: '已加入购物车',
								icon: 'success'
							});
							// 添加成功后跳转到购物车页面
							uni.navigateTo({
								url: '/pages/cart/cart'
							});
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '加入购物车失败',
							icon: 'none'
						});
					}
				});
			}
		}
	}
</script>

<style>
	.product-detail {
		padding: 10px;
	}

	.product-detail image {
		width: 100%;
		height: 300px;
	}

	.product-info {
		padding: 10px;
	}

	.product-name {
		font-size: 20px;
		font-weight: bold;
	}

	.product-price {
		color: #ff0000;
		font-size: 18px;
	}

	.quantity-selector {
		display: flex;
		align-items: center;
		margin: 10px 0;
	}

	.quantity-selector input {
		width: 50px;
		text-align: center;
		margin: 0 10px;
	}

	.quantity-selector button {
		width: 30px;
		height: 30px;
	}
</style>